let dayList = [], now = new Date(), calendarMonth = '',
  calendarAbbr = 'ALL,CN,HK,TW,US,DE,FR,JP,CA,IN,AU,SA,ID,ES,GB,MX,RU,KR,TR,IT,BR,ZA,MO,AR',
  calendarAbbrCopy = calendarAbbr,
  originAbbr = calendarAbbr,
  countryListCopy = [],
  initY = now.getFullYear(),
  ny = initY, ty = initY,
  initM = now.getMonth(),
  nm = initM, tm = initM,
  initD = now.getDate(),
  nd = initD, td = initD,

  weekArray = ['日', '一', '二', '三', '四', '五', '六'],
  active = ny + '-' + (nm + 1) + '-' + nd,
  currDateCal = DateUtils.date2Dt(new Date()),
  fCodeCal = '004007',
  activeStatus = 3 // 默认状态为3 日视图
let countryList = [
  {'code': 'ALL', 'name': '全部', 'selected': true},
  {'code': 'CN', 'name': '中国', 'selected': false},
  {'code': 'HK', 'name': '中国香港', 'selected': false},
  {'code': 'TW', 'name': '中国台湾', 'selected': false},
  {'code': 'US', 'name': '美国', 'selected': false},
  {'code': 'DE', 'name': '德国', 'selected': false},
  {'code': 'FR', 'name': '法国', 'selected': false},
  {'code': 'JP', 'name': '日本', 'selected': false},
  {'code': 'CA', 'name': '加拿大', 'selected': false},
  {'code': 'IN', 'name': '印度', 'selected': false},
  {'code': 'AU', 'name': '澳大利亚', 'selected': false},
  {'code': 'SA', 'name': '沙特', 'selected': false},
  {'code': 'ID', 'name': '印尼', 'selected': false},
  {'code': 'ES', 'name': '西班牙', 'selected': false},
  {'code': 'GB', 'name': '英国', 'selected': false},
  {'code': 'MX', 'name': '墨西哥', 'selected': false},
  {'code': 'RU', 'name': '俄罗斯', 'selected': false},
  {'code': 'KR', 'name': '韩国', 'selected': false},
  {'code': 'TR', 'name': '土耳其', 'selected': false},
  {'code': 'IT', 'name': '意大利', 'selected': false},
  {'code': 'BR', 'name': '巴西', 'selected': false},
  {'code': 'ZA', 'name': '南非', 'selected': false},
  {'code': 'MO', 'name': '中国澳门', 'selected': false},
  {'code': 'AR', 'name': '阿根廷', 'selected': false}
]


//向右移动需要调用的函数
function moveRight() {
  let temp = dayList
  let tempArr = temp[temp.length - 1].day.split('-')
  ny = tempArr[0]
  nm = tempArr[1] - 1
  nd = tempArr[2]
  initDate(1, 8)
}


// 向左移动滚动条
function moveLeft() {
  let temp = dayList
  let tempArr = temp[0].day.split('-')
  ny = tempArr[0]
  nm = tempArr[1] - 1
  nd = tempArr[2]
  initDate(-7, 0, 1)
}


function initDate(start, end, flag) {
  let o, day
  let tempDay = []
  for (let i = start; i < end; i++) {
    o = {}
    day = countDate(ny, nm, nd, i)
    o.day = day
    if (o.day === (initY + '-' + (initM + 1) + '-' + initD)) {
      o.isToday = true
    }
    let dayStr = day.split('-')
    o.week = countWeek(dayStr[0] + '-' + (dayStr[1] < 10 ? ('0' + dayStr[1]) : dayStr[1]) + '-' + (dayStr[2] < 10 ? ('0' + dayStr[2]) : dayStr[2]))
    tempDay.push(o)
  }
  $('.index-calendar-ny').html(ny + '年' + (nm + 1) + '月')
  // 左移将数据添加到前面,右移添加到后面
  dayList = !flag ? dayList.concat(tempDay) : tempDay.concat(dayList)
  assembleDate()
}

function initCalendar() {
  countryListCopy = JSON.parse(JSON.stringify(countryList))
  dayList = []
  initDate(-7, 7)

  $('.index-calendar-line').scrollLeft(225)

  $('.index-calendar-line').scroll(function () {
    if (activeStatus === 3 || activeStatus === 1) {
      let scrollLeft = $(this).scrollLeft()//滚动条位置
      let windowWidth = $(this).width()//显示区域宽度
      let scrollWidth = $(this)[0].scrollWidth //页面内容区域实际宽度
      if (scrollLeft > pm.scrollLeft) {
        if ((scrollLeft + windowWidth) >= (scrollWidth - 50)) {
          moveRight()
        }
      } else {
        if (scrollLeft < 50) {
          moveLeft()
          dayList.splice(dayList.length - 7, 7)
          $('.index-calendar-line').scrollLeft(100)
        }
      }
      pm.scrollLeft = scrollLeft
    }
  })
}

//组转日期栏
function assembleDate() {
  let htmlStr = ''
  dayList.forEach(function (item) {
    htmlStr += '<div class=\'index-calendar-day flex-column align-items-center justify-content-center mr10 ' + (item.day === active ? 'index-calendar-day-active' : '') + ' \' onclick=\'selectDay("' + item.day + '")\'>'
    htmlStr += '<div class=\'index-calendar-day-w fspx12 ' + (item.day === active ? 'index-calendar-day-w-active' : '') + '\'>' + item.week + '</div>'
    htmlStr += '<div class=\'index-calendar-day-d fspx18 ff600 ' + (item.isToday ? 'index-calendar-day-d-active-now' : '') + ' ' + (item.day === active ? 'index-calendar-day-d-active' : '') + ' \'>' + item.day.split('-')[2] + '</div>'
    htmlStr += '</div>'
  })
  $('.index-calendar-date').html(htmlStr)
}

function assembleMonth() {
  let tempM = active.split('-')[1]
  let htmlStr = ''
  for (let i = 1; i <= 12; i++) {
    htmlStr += '<div class=\'index-calendar-day ' + (i === parseInt(tempM) ? 'index-calendar-day-active' : '') + '  justify-content-center flex-column align-items-center mr10\'  onclick=\'selectMonth("' + active.split('-')[0] + '-' + i + '")\' >'
    htmlStr += '<div class=\'index-calendar-day-d ' + (i === parseInt(tempM) ? 'index-calendar-day-d-active' : '') + ' fspx16 ff600\'>' + i + '月</div>'
    htmlStr += '</div>'
  }
  $('.index-calendar-date').html(htmlStr)
}

//选择某一天
function selectDay(time) {
  active = time
  td = active.split('-')[2]
  $('.index-calendar-ny').html(active.split('-')[0] + '年' + active.split('-')[1] + '月')
  assembleDate()
  currDateCal = DateUtils.str2Dt(active.split('-')[0] + '-' + active.split('-')[1] + '-' + active.split('-')[2] + ' 08:00:00')
  pm[fCodeCal][fCodeCal].pageNum = 1
  // dealCalendar(fCodeCal)
  $('.scoll-area').animate({scrollTop: 0}, 200)
  calendarChange(3)
}

function selectMonth(time) {
  active = time
  let monthSelect = active.split('-')
  $('.index-calendar-ny').html(monthSelect[0] + '年' + monthSelect[1] + '月')
  currDateCal = ''
  calendarMonth = monthSelect[0] + '-' + (monthSelect[1] < 10 ? ('0' + monthSelect[1]) : monthSelect[1])
  assembleMonth()
  pm[fCodeCal][fCodeCal].pageNum = 1
  $('.scoll-area').animate({scrollTop: 0}, 200)
  dealCalendar(fCodeCal)
}

//计算日期，几天前，几天后...
function countDate(y, m, d, num) {
  let date = new Date(y, m, d)
  date.setDate(date.getDate() + num)
  //num是正数表示之后的时间，num负数表示之前的时间，0表示今天
  return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
}

// 计算是星期几
function countWeek(datestr) {
  return weekArray[new Date(datestr).getDay()]
}

// 1、今  2、月 3、日
function calendarChange(val) {
  activeStatus = val
  $('.index-calendar-nyr').removeClass('index-calendar-nyr-active')
  $('.index-calendar-nyr').eq(val).addClass('index-calendar-nyr-active')
  if (1 === val) { // 今
    ny = ty = now.getFullYear(),
    nm = tm = now.getMonth(),
    nd = td = now.getDate(),
    active = ty + '-' + (tm + 1) + '-' + td
    dayList = []
    currDateCal = DateUtils.date2Dt(new Date())
    calendarMonth = ''
    $('.index-calendar-line').scrollLeft(225)
    initDate(-7, 7)
  } else if (2 === val) { // 月视图
    currDateCal = ''
    let monthVal = active.split('-')
    calendarMonth = monthVal[0] + '-' + (monthVal[1] < 10 ? ('0' + monthVal[1]) : monthVal[1])
    assembleMonth()
  } else if (3 === val) { //日视图
    ny = active.split('-')[0]
    nm = active.split('-')[1] - 1
    nd = td
    dayList = []
    calendarMonth = ''
    currDateCal = DateUtils.str2Dt(active.split('-')[0] + '-' + active.split('-')[1] + '-' + nd + ' 08:00:00')
    $('.index-calendar-line').scrollLeft(225)
    initDate(-7, 7)
  }
  pm[fCodeCal][fCodeCal].pageNum = 1
  dealCalendar(fCodeCal)
  $('.scoll-area').animate({scrollTop: 0}, 200)
}

function selectCalendar() {
  let nyr = active.split('-')
  let paramDate = nyr[0] + '-' + (nyr[1] < 10 ? ('0' + nyr[1]) : nyr[1])
  paramDate = activeStatus !== 2 ? (paramDate + '-' + (nyr[2] < 10 ? ('0' + nyr[2]) : nyr[2])) : paramDate
  // 传type ，如果传入的值是2，则调用年月日期选择器
  jsBridge.callBridge('nativeCalendar', {
    date: paramDate,
    dateFormat: activeStatus === 2 ? 'yyyy-MM' : 'yyyy-MM-dd'
  }).then(data => {
    if (data.date && data.date !== paramDate) {
      let nyrGet = data.date.split('-')
      ny = ty = nyrGet[0]
      nm = tm = parseInt(nyrGet[1]) - 1
      nd = td = nyrGet[2] ? parseInt(nyrGet[2]) : ''
      active = ny + '-' + (nm + 1) + (nd ? ('-' + nd) : '')
      if (nd) {
        currDateCal = DateUtils.str2Dt(active.split('-')[0] + '-' + active.split('-')[1] + '-' + active.split('-')[2] + ' 08:00:00')
        initCalendar()
      } else {
        let monthVal = active.split('-')
        calendarMonth = monthVal[0] + '-' + (monthVal[1] < 10 ? ('0' + monthVal[1]) : monthVal[1])
        $('.index-calendar-ny').html(monthVal[0] + '年' + monthVal[1] + '月')
        assembleMonth()
      }
      pm[fCodeCal][fCodeCal].pageNum = 1
      dealCalendar(fCodeCal)
    }
  })
}

function calendarShow() {
  dealCountryList()
  $('.index-info-cal-show').show()
}

function dealCountryList() {
  let htmlStr = ''
  $.each(countryList, function (i, item) {
    htmlStr += '<div class="index-info-cal-item mb10 calendar-country-item-' + item.code + ' ' + (item.selected ? ' index-info-cal-item-active' : '') + ' fleft" onclick="selectCountry(\'' + item.code + '\')">' + item.name + '</div>'
  })
  $('.index-info-cal-box').html(htmlStr)

}

function selectCountry(code) {
  $.each(countryList, function (i, item) {
    if (code === 'ALL') {
      if (!item.selected) {
        $('.index-info-cal-item').removeClass('index-info-cal-item-active')
        $('.calendar-country-item-ALL').addClass('index-info-cal-item-active')
      } else {
        $('.index-info-cal-item').removeClass('index-info-cal-item-active')
      }
      item.selected = !item.selected
      calendarAbbr = item.selected ? originAbbr : ''
      countryList.forEach(function (it, index) {
        if (index > 0) {
          it.selected = false
        }
      })
      return false
    } else {
      if (item.code === code) {
        if (!item.selected) {
          $('.calendar-country-item-' + code).addClass('index-info-cal-item-active')
          item.selected = !item.selected
          setSelectedState(item.selected, item.code)
          $('.calendar-country-item-ALL').removeClass('index-info-cal-item-active')
          setSelectedState(false, 'ALL')
        } else {
          $('.calendar-country-item-' + code).removeClass('index-info-cal-item-active')
          item.selected = !item.selected
          setSelectedState(item.selected, item.code)
        }
      }
    }
  })
}


//设置选择状态
function setSelectedState(flag, code) {
  let str = ''
  $.each(countryList, function (i, item) {
    if (Utils.notEmpty(code)) {//指定了code
      if (code === item.code) {
        item.selected = flag
      }
    } else {
      item.selected = flag
    }

    //重新计算选中列表
    if (item.selected) {

      str += item.code + ','
    }
  })
  if (Utils.notEmpty(str)) {
    calendarAbbr = str.substr(0, str.length - 1)
  } else {//处理成一个都没选中
    calendarAbbr = 'noSelected'
    selectCountry('ALL')
  }
}

function calendarSure() {
  $('.index-info-cal-show').hide()
  countryListCopy = JSON.parse(JSON.stringify(countryList))
  calendarAbbrCopy = calendarAbbr
  pm[fCodeCal][fCodeCal].pageNum = 1
  dealCalendar(fCodeCal)

}

function calendarCancle() {
  countryList = JSON.parse(JSON.stringify(countryListCopy))
  calendarAbbr = calendarAbbrCopy
  $('.index-info-cal-show').hide()
}
